package com.sinog.biz.schedule;

import com.sinog.biz.BizApplication;
import com.sinog.biz.mapper.havexml.other.DataStatisticsContrastMapper;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.DataSourceCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;

/**
 * @desc 数据统计定时任务， 每晚
 * @author ybl
 * @date 2022/8/8
 */
@Slf4j
@Component
@Configuration
public class DataStatsSchedule {

    /**
     * 部级资源库
     */
    private JdbcTemplate bujiJdbcTemplate;
    @Autowired
    private DataStatisticsContrastMapper dataStatisticsContrastMapper;

    @Scheduled(cron = "${gkzx.azbj.pstatexztj.cron}")
    private void dataStats() {
        log.info("\n>>>>>>>>>>>starting......每日新增状态数量统计<<<<<<<<<<");
        //拿到本省新增的数据量
        List<Map<String,Object>> mapList = dataStatisticsContrastMapper.getStateStat(CodeUrlUtils.getLocalCode());
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        //检测全部数据源是否可用
        boolean allRunning = DataSourceCheckUtils.checkRunningStatus(bujiJdbcTemplate);
        if(true){
            StringBuilder sql = new StringBuilder("INSERT INTO data_statistics_contrast " + "(amount,pstate,adduserid,addusername,province) " + "VALUES ");
            if(mapList.isEmpty()) {
                return;
            }
            for(Map<String,Object> map : mapList) {
                sql.append("(").append(map.get("count")).append(",").append("'").append((String)map.get("pstate"))
                   .append("',").append("'").append((String)map.get("id")).append("',").append("'")
                   .append((String)map.get("name")).append("',").append("'").append((String)map.get("province"))
                   .append("'),");
            }
            log.info("\n执行的SQL：" + sql.substring(0,sql.length() - 1));
            bujiJdbcTemplate.update(sql.substring(0,sql.length() - 1));
            log.info("\n>>>>>>>>>>>ending......每日新增状态数量统计<<<<<<<<<<");
        } else {
            log.error("检测到数据源不可用,本次执行定时任务失败!");
        }
    }
}